<template>
  <div class="app-container">
    <el-row :gutter="20" v-if="parent">
        <div slot="header" class="fz">
          数据概括
        </div>
        <div class="text item fz" style="text-align:center">
          <el-row>
            <el-col :span="6">
              <el-card class="box-card" style="margin:0 10px;font-size: 20px;">
                <p>昨日收入</p>
                <p class="big_font">{{statisticalData.yesterdayIncome}}</p>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="box-card" style="margin:0 10px;font-size: 20px;">
                <p>今日收入</p>
                <p class="big_font">{{statisticalData.todayIncome}}</p>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="box-card" style="margin:0 10px;font-size: 20px;">
                <p>总收入</p>
                <p class="big_font">{{statisticalData.totalIncome}}</p>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="box-card" style="margin:0 10px;font-size: 20px;">
                <p>账户余额</p>
                <p class="big_font">{{statisticalData.balance}}</p>
              </el-card>
            </el-col>
          </el-row>
        </div>

    </el-row>
    <el-row  :gutter="20" style="margin-top:20px;font-size: 14px;">
      <el-col :span="cssWidth > 950 ? 8 : 24" v-for="(item) of channelList" :key="item.channelId" class="min-div" v-if="item.status == 0">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <div class="clearfix-sun">
              <div style="display: flex;justify-content: flex-start;align-items: center;">
<!--                <el-image style="width:20px;height:20px;margin-right:10px;" :src="item.logo" />-->
                <span>{{item.channelName}} 一 {{item.channelId}}</span>
                <span v-if="chooseUserName">（{{chooseUserName}}）</span>
              </div>
              <div>
<!--                <el-button type="text" :disabled="item.status == 1" class="min-btn"-->
<!--                  @click="handelImportAccount(item)">批量导入</el-button>-->
                <el-button style="padding: 3px 0px" type="text" class="min-btn" v-if="item.channelId == 505" @click="handelTongbu(item)">
                  手动刷新（{{item.totalAccount}}）
                </el-button>
                <el-button style="padding: 3px 0px" type="text" :disabled="item.status == 1" class="min-btn" v-if="item.channelId != 505"
                  @click="handelAddAccount(item)">
                  添加账号（{{item.totalAccount}}）
                </el-button>
              </div>
            </div>
          </div>


          <div class="text item" style="text-align:center">
            <el-row>
              <el-col :span="8">
                <p>昨日收入</p>
                <p class="big_font">{{item.yesterdayIncome}}元</p>
              </el-col>
              <el-col :span="8">
                <p>今日收入</p>
                <p class="big_font">{{item.todayIncome}}元</p>
              </el-col>
              <el-col :span="8">
                <p>总收入</p>
                <p class="big_font">{{item.totalIncome}}元</p>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>


    <!-- 添加账号对话框 -->
    <el-dialog :title="addAccount.title" :visible.sync="addAccount.open" :width="isPhone?'90%':'650px'" :close-on-click-modal="false"
      append-to-body>
      <el-form ref="ruleForm" :model="addAccount.form" :rules="addAccountRules" label-width="120px">
        <el-form-item label="抖音ID" prop="douyinId" v-if="addAccount.form.isNeedDouYinId == 0">
          <el-input v-model="addAccount.form.douyinId" placeholder="例如：12345678" />
        </el-form-item>
<!--        <el-form-item label="cookie" prop="ck" v-if="addAccount.form.isNeedCk == 0">-->
<!--          <el-input v-model="addAccount.form.ck" placeholder="例如：sessionid=716d26cc8eefd0a637205ba4ea23c2a0" />-->
<!--        </el-form-item>-->
        <el-dialog width="20%" title="验证码获取CK" :visible.sync="sendMobileCodeInnerVisible" :close-on-click-modal="false"
          append-to-body>
          <el-form :model="mobileCodeForm" label-width="100px">
            <el-form-item label="手机号码">
              <el-input v-model="mobileCodeForm.mobile" placeholder="请输入手机号码" />
            </el-form-item>
            <el-form-item label="验证码">
              <el-input v-model="mobileCodeForm.code" placeholder="请输入验证码" />
            </el-form-item>
            <el-form-item style="text-align: right;">
              <el-button type="primary" @click="sendMobileCode">发送验证码</el-button>
              <el-button type="primary" @click="submitMobileCode">提交</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="addAccount.form.type" placeholder="请选择设备类型" size="small" style="width:35%;">
            <el-option label="安卓" value="2" />
            <el-option label="苹果" value="1" />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="设备编码" prop="deviceId" v-if="(addAccount.form.type == 1 && addAccount.form.channelId != 506)-->
<!--          || (addAccount.form.type == 2)">-->
        <el-form-item label="设备编码" prop="deviceId" v-if="addAccount.form.isNeedDeviceId == 0">
          <el-input v-model="addAccount.form.deviceId" placeholder="例如：12385s1d515x1a5d51415">
            <el-button v-if="addAccount.form.channelId != 506" type="primary" slot="append" @click="getIidFn">获取iid</el-button>
          </el-input>
        </el-form-item>
        <div v-if="addAccount.form.isFixed == 0">
          <el-form-item v-for="(fixedAmount, index) in addAccount.form.fixedAmounts" :label="'额度' + (index + 1)"
            :key="fixedAmount.key" :prop="'domains.' + index + '.value'">
            <el-row>
              <el-col :span="3">
                <el-input v-model="fixedAmount.money" placeholder="额度"></el-input>
              </el-col>
              <el-col :span="1" style="text-align:center">
                <span>一</span>
              </el-col>
              <el-col :span="13">
                <el-input v-model="fixedAmount.payUrl" placeholder="充值链接"></el-input>
              </el-col>
              <el-col :span="3" offset="1">
                <el-button type="primary" plain icon="el-icon-plus" @click="addFixedAmount(index+1)"></el-button>
              </el-col>
              <el-col :span="3" v-if="index != 0">
                <el-button type="danger" plain icon="el-icon-delete" @click="removeFixedAmount(fixedAmount)">
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </div>
        <el-form-item label="指定代理信息" prop="proxyModel">
          <el-select v-model="addAccount.form.proxyModel" placeholder="请选择代理信息" size="small" style="width:35%;">
            <el-option v-for="item in proxyList" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
          <div style="display: inline-block;width:65%;" v-if="addAccount.form.proxyModel == 1">
             <el-input v-model="addAccount.form.proxyHost" placeholder="IP" style="width:70%;" size="small"></el-input>
             <el-input v-model="addAccount.form.proxyPort" placeholder="端口" style="width:30%;" size="small"></el-input>
          </div>
<!--          <div style="display: inline-block;width:65%;" v-if="proxyModule == 2">-->
<!--             <el-input v-model="proxyAreaName" placeholder="选择指定区域代理" size="small" @focus="regionDing('')"></el-input>-->
<!--          </div>-->
          <!-- <el-row>
            <el-col :span="20">
              <el-input v-model="addAccount.form.proxyHost" placeholder="IP"></el-input>
            </el-col>
            <el-col :span="4">
              <el-input v-model="addAccount.form.proxyPort" placeholder="端口"></el-input>
            </el-col>
          </el-row> -->
        </el-form-item>
        <el-form-item label="地区" prop="proxyArea" v-if="addAccount.form.proxyModel == 2">
          <el-cascader v-model="addAccount.form.proxyArea" :options="regionList" :props="props" :show-all-levels="false" filterable @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="所属分组" prop="groupId">
          <el-select v-model="addAccount.form.groupId" placeholder="请选择所属分组" size="small" style="width:35%;">
            <el-option v-for="item in accountGroupList" :key="item.groupId" :label="item.groupName"
              :value="item.groupId" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属核销" prop="userId">
          <el-cascader v-model="chooseArr" :props="writeOffProps" :show-all-levels="false"></el-cascader>
        </el-form-item>
        <el-form-item label="日限额" prop="dailyLimitQuota">
          <el-input v-model="addAccount.form.dailyLimitQuota" placeholder="为空或0则不限制" />
        </el-form-item>
        <el-form-item label="总限额" prop="totalLimitQuota">
          <el-input v-model="addAccount.form.totalLimitQuota" placeholder="为空或0则不限制" />
        </el-form-item>
        <el-form-item label="收款限制" style="text-align:center">
          <el-row>
            <el-col :span="11">
              <el-input v-model="addAccount.form.cashierNlt" placeholder="为空或0则不限制（大于等于）" />
            </el-col>
            <el-col :span="2">
              <span>一</span>
            </el-col>
            <el-col :span="11">
              <el-input v-model="addAccount.form.cashierNmt" placeholder="为空或0则不限制（小于等于）" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addAccount.form.remark" placeholder="请输入备注" />
        </el-form-item>
<!--        <el-form-item label="扫码" prop="remark">-->
<!--          <el-button type="primary" @click="getCodeImgFn">获取二维码</el-button>-->
<!--        </el-form-item>-->
        <el-form-item label="iid" prop="installId" v-if="addAccount.form.channelId == 506 && addAccount.form.type == 1">
          <el-input v-model="addAccount.form.installId" placeholder="请输入iid" />
        </el-form-item>
        <el-form-item label="CK" prop="json" v-if="addAccount.form.isNeedCk == 0">
          <el-input v-model="addAccount.form.json" placeholder="请扫码获取json，并填入" />
        </el-form-item>
        <el-form-item style="text-align: right;">
          <el-button type="primary" v-if="addAccount.form.isNeedSaoma == 0" :loading="submitCodeButtonLoading" @click="submitAddAccount('ruleForm', 1)">扫 码</el-button>
          <el-button type="primary" v-if="addAccount.form.isNeedMobile == 0" :loading="submitByMobileLoading" @click="submitAddAccount('ruleForm', 3)">短 信</el-button>
          <el-button type="primary" v-if="addAccount.form.isNeedPwd == 0" :loading="submitByPwdLoading" @click="submitAddAccount('ruleForm', 4)">密 码</el-button>
          <el-button type="primary" v-if="(addAccount.form.channelId != 506) || (addAccount.form.channelId == 506 && addAccount.form.type == 1)"
                     :loading="submitAddAccountButtonLoading" @click="submitAddAccount('ruleForm', 2)">确 定</el-button>
          <el-button @click="cancel('ruleForm')">取 消</el-button>
        </el-form-item>
      </el-form>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitAddAccountButtonLoading" @click="submitAddAccount(ruleForm)">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div> -->
      <el-dialog :width="isPhone?'90%':'650px'" title="绑定手机号" :visible.sync="bindingVisible" :close-on-click-modal="false"
                 append-to-body>
        <el-form :model="mobileCodeForm" label-width="100px">
          <el-form-item label="手机号码">
            <el-input v-model="mobileCodeForm.mobile" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="验证码">
            <el-input v-model="mobileCodeForm.code" placeholder="请输入验证码" />
          </el-form-item>
          <el-form-item style="text-align: right;">
            <el-button type="primary" :disabled="count != 60" @click="sendCodeFn">{{ codeMsg }}</el-button>
            <el-button type="primary" :loading="addButtonLoading" @click="submitMobile">提交</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog :width="isPhone?'90%':'650px'" title="手机号密码" :visible.sync="pwdVisible" :close-on-click-modal="false"
                 append-to-body>
        <el-form :model="mobilePwdForm" label-width="100px">
          <el-form-item label="手机号码">
            <el-input v-model="mobilePwdForm.mobile" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="mobilePwdForm.password" type="password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item style="text-align: right;">
            <el-button type="primary" :loading="addByPwdLoading" @click="submitPwd">提交</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog :width="isPhone?'90%':'650px'" :close-on-click-modal="false" class="region" :visible.sync="regionDialog" append-to-body>
          <div class="region-head">
             <span style="font-size: 19px;font-weight: bold;">全部地区</span>
             <el-input v-model="regionModule" style="width:200px;margin-left:20px;font-size: 16px;" size="small" class="region-input"></el-input>
             <el-button type="primary" @click="handleSearch" size="small" style="border-radius: 0;font-size: 16px;height: 32px;">搜索</el-button>
          </div>
          <div style="overflow: auto;height: 500px;">
            <div style="margin-bottom:10px;" v-for="item in regionList" :key="item.label">
              <div style="font-size: 16px;background: #f7f8fb;padding: 10px 20px;text-align: left;margin-bottom:10px;">{{item.label}}</div>
              <div class="city-choice">
                <div :class="proxyAreaCode == val.id ? 'city-itme-btn' : 'city-itme'" v-for="val in item.children" :key="val.id" @click="handleChoice(val)" @dblclick="handleBd(val)">{{val.label}}</div>
              </div>
            </div>
          </div>
          <div style="height:60px;text-align: center;line-height: 80px;">
            <el-button type="primary" @click="regionDialog = false">确 定</el-button>
          </div>
       </el-dialog>
      <el-dialog :width="isPhone?'90%':'300px'" :close-on-click-modal="false" class="region" :visible.sync="codeDialog" append-to-body @close="handleClose">
        <div class="box-code">
          <img class="code-img" :src="codeSrc" alt="" />
<!--          <div class="box-state" v-if="codeStatus == 'expired'">-->
<!--            <div class="state">-->
<!--              <div class="text">已过期</div>-->
<!--            </div>-->
<!--          </div>-->
        </div>
<!--        <div class="time">{{expireTime}}</div>-->
<!--        <div style="height:60px;text-align: center;line-height: 80px;">-->
<!--          <el-button type="primary" @click="getCodeFn">刷 新</el-button>-->
<!--        </div>-->
      </el-dialog>
    </el-dialog>


    <el-dialog title="批量导入" :visible.sync="upload.open" :width="isPhone?'90%':'500px'" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :on-error="handleFileError" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :loading="submitFileFormLoading">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>


</template>

<script>
  import {
    listChannel
  } from "@/api/merchant/channel";

  import {
    listAccountGroup
  } from "@/api/merchant/accountGroup";

  import {
    addAccount,
    areaList,
    getQrcodeByDID,
    checkQrcode,
    jsDeviceInfo,
    sendCode,
    smsLogin, tongbu, getDIdAndIid, loginByPwd
  } from '@/api/merchant/account'

  import {
    getToken
  } from "@/utils/auth";

  import {
    sendMobileCode,
    submitMobileCode
  } from "@/api/merchant/dy";
  import {
    initIndexData
  } from "@/api/merchant/index";
  import {
    listAllWriteOff
  } from "@/api/merchant/writeOff"
  import { formatTime } from '@/utils/index'
  import { mapGetters } from 'vuex'

  export default {
    name: "ChannelList",
    data() {
      return {
        //是否现实二维码弹出层
        sendMobileCodeInnerVisible: false,
        //抖音登录
        douyinLogin: {
          qrcode: '',
          token: '',
        },
        //定时器
        timer: null,
        // 导入参数
        upload: {
          // 是否显示弹出层）
          open: false,
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: '',
          //通道ID
          channelId: null,
        },
        //上传地址
        uploadUrl: process.env.VUE_APP_BASE_API + "/account/importData/",
        //批量导入表单
        importAccountform: {},
        //通道列表
        channelList: [],
        //通道的二维数组
        channelArray: [],
        //账号分组列表
        accountGroupList: [],
        //提交添加账号按钮loading
        submitAddAccountButtonLoading: false,
        submitCodeButtonLoading: false,
        //提交导入账号按钮loading
        submitFileFormLoading: false,
        //提交短信绑定按钮loading
        submitByMobileLoading: false,
        //提交手机号密码按钮loading
        submitByPwdLoading: false,
        //提交绑定按钮loading
        bindMobileLoading: false,
        //添加账号
        addAccount: {
          open: false,
          title: '',
          form: {
            groupId: 0,
            json: '',
            deviceId: '',
            installId: '',
            fixedAmounts: [{
              key: '0',
              money: '',
              payUrl: ''
            }],
          },
        },
        proxyList:[
          {label:'无',value:0},
          {label:'指定代理',value:1},
          {label:'指定区域代理',value:2},
        ],
        proxyModule:0,
        regionDialog:false,
        regionList: [],
        proxyArea:'',
        proxyAreaCode:'',
        proxyAreaName:'',
        regionModule:'',
        props: {
          // checkStrictly: true,
          value: 'id',
          label: 'label',
          children: 'children',
        },
        //手机密码表单
        mobilePwdForm: {
          mobile: undefined,
          password: undefined
        },
        //手机验证码表单
        mobileCodeForm: {
          mobile: undefined,
          code: undefined
        },
        //添加账号表单校验
        addAccountRules: {
          douyinId: [{
            required: true,
            message: "抖音ID不能为空",
            trigger: "blur"
          }],
          ck: [{
            required: true,
            message: "cookie不能为空",
            trigger: "blur"
          }],
          type: [{
            required: true,
            message: "请选择设备类型",
            trigger: "change"
          }],
          proxyModule: [{
            required: true,
            message: "请选择指定代理",
            trigger: "change"
          }],
          proxyArea: [{
            required: true,
            message: "请选择代理区域",
            trigger: "change"
          }],
          /*           deviceId: [{
                      required: true,
                      message: "设备编号不能为空",
                      trigger: "blur"
                    }], */
          // json: [{
          //   required: true,
          //   message: "请扫码获取CK，并填入",
          //   trigger: "blur"
          // }]
        },
        options: [],
        shareScope: [],
        shareScopeEnd: [],
        areaList: [],
        areaCode: '',
        parent: this.$store.state.user.parent,
        statisticalData: {},
        cssWidth:document.documentElement.clientWidth,
        userId: 0,
        codeDialog: false,
        codeSrc: '',
        expireTime: '',
        codeStatus: '',
        deviceInfo: {},
        bindingVisible: false,
        pwdVisible: false,
        count: 60,
        addButtonLoading: false,
        addByPwdLoading: false,
        chooseArr: [],
        writeOffProps: {
          checkStrictly: true,
          lazy: true,
          // leaf: true,
          lazyLoad (node, resolve) {
            const { value } = node;
            listAllWriteOff({userId: value}).then(res => {
              const nodes = res.map(item => {
                return {
                  value: item.userId,
                  label: item.userName,
                  leaf: item.children < 1,
                }
              });
              resolve(nodes)
            })
          }
        }
      };
    },
    computed: {
      ...mapGetters(['isMobile', 'userInfo', 'chooseUserId', 'chooseUserName']),
      isPhone() {
        let info = navigator.userAgent;
        //通过正则表达式的test方法判断是否包含“Mobile”字符串
        let isPhone = /mobile/i.test(info);
        //如果包含“Mobile”（是手机设备）则返回true
        return isPhone;
      },
      codeMsg() {
        if (this.count == 60) {
          return '发送验证码'
        }else {
          return `${this.count}秒后重发`
        }
      },
    },
    watch: {
      'addAccount.form.proxyModel': {
        handler: function() {
          if (this.addAccount.form.proxyModel == 2) {
            this.regionDing('');
          }
        },
        immediate: true
      },
      // 'addAccount.form.type': {
      //   handler: function() {
      //     if (this.addAccount.form.type == 1 && this.addAccount.form.channelId == 506) {
      //       this.getAccountSysInfo();
      //     }else {
      //       this.addAccount.form.installId = '';
      //       this.addAccount.form.deviceId = '';
      //     }
      //   },
      //   immediate: true
      // },
    },
    created() {
      //获取账号分组列表
      this.getAccountGroupList();
    },
    mounted() {
      console.log(this.userInfo, '11')
      this.getList();
    },
    methods: {
      getAccountSysInfo() {
        getDIdAndIid().then(res => {
          if (res.code == 200) {
            this.iid = res.data.iid;
            this.addAccount.form.installId = res.data.iid;
            this.addAccount.form.deviceId = res.data.did;
          }
        })
      },
      getCodeImgFn() {
        getQrcodeByDID(this.addAccount.form).then(res => {
          this.codeSrc = `${res.data.qrcode}`;
          this.iid = res.data.iid;
          this.codeDialog = true;
        });
      },
      getIidFn() {
        getQrcodeByDID(this.addAccount.form).then(res => {
          this.codeSrc = `${res.data.qrcode}`;
          this.iid = res.data.iid;
        });
      },
      handelTongbu() {
        tongbu({}).then(res => {
          this.$modal.msgSuccess(res.msg);
          this.getList();
        })
      },
      handleClose() {
        this.codeDialog = false;
        clearInterval(this.timer);
      },
      /** 查询通道信息列表 */
      getList() {
        listChannel(this.chooseUserId).then(response => {
          this.channelList = response.data;
          const pages = []
          this.channelList.forEach((item, index) => {
            const page = Math.floor(index / 3) //4代表4条为一行，随意更改
            if (!pages[page]) {
              pages[page] = []
            }
            pages[page].push(item)
          })
          this.channelArray = pages;
        });
        if (this.$store.state.user.parent) {
          initIndexData().then(response => {
            this.statisticalData = response.data;
          });
        }
      },
      /** 查询账号分组列表 */
      getAccountGroupList() {
        let opt = {};
        if (this.chooseUserId != 0) {
          opt.userId = this.chooseUserId;
        }
        listAccountGroup(opt).then(response => {
          this.accountGroupList = response.rows;
        });
      },
      /** 处理添加账号按钮 */
      handelAddAccount(channel) {
        this.reset();
        let channelId = channel.channelId;
        this.addAccount.form.channelId = channelId;
        this.addAccount.form.isFixed = channel.isFixed;
        this.addAccount.form.isNeedDouYinId = channel.isNeedDouYinId;
        this.addAccount.form.isNeedCk = channel.isNeedCk;
        this.addAccount.form.isNeedDeviceId = channel.isNeedDeviceId;
        this.addAccount.form.isNeedMobile = channel.isNeedMobile;
        this.addAccount.form.isNeedPwd = channel.isNeedPwd;
        this.addAccount.form.isNeedSaoma = channel.isNeedSaoma;
        this.addAccount.open = true;
        this.addAccount.title = channel.channelName;
        this.options = [];
        this.shareScope = [];
        this.shareScopeEnd = [];
        this.areaList = [];
        this.areaCode = '';
        this.addAccount.form.userId = this.userId;
        let that = this;
        /*         setTimeout(function () {
                  that.mobileCodeForm = {};
                  that.sendMobileCodeInnerVisible = true;
                }, 200); */
      },
      /** 取消二维码弹窗 */
      cancelQrcode() {
        this.sendMobileCodeInnerVisible = false;
        clearInterval(this.timer);
      },
      /** 处理账号导入按钮 */
      handelImportAccount(channel) {
        this.upload.open = true;
        var channelId = channel.channelId;
        this.upload.channelId = channelId;
        this.upload.url = this.uploadUrl + channelId;
      },
      /** 提交添加账号 */
      submitAddAccount(formName, type) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addAccount.form.areaCode = this.areaCode
            // this.addAccount.form.proxyModel = this.proxyModule
            if (this.addAccount.form.proxyModel == 2) {
              this.addAccount.form.proxyAreaCode = this.proxyAreaCode
              this.addAccount.form.proxyAreaName = this.proxyAreaName
            }
            let opt = Object.assign({}, this.addAccount.form, {});
            if (this.chooseArr.length) {
              opt.userId = this.chooseArr[this.chooseArr.length - 1];
              this.addAccount.form.userId = this.chooseArr[this.chooseArr.length - 1];
            }
            opt.installId = this.iid;
            // addAccount(opt).then(response => {
            //   this.$modal.msgSuccess("新增成功");
            //   this.getList();
            //   this.addAccount.open = false;
            //   this.reset();
            // }).finally(() => {
            //   this.submitAddAccountButtonLoading = false;
            // });
            // if (this.addAccount.form.channelId == 506) {
            if (type == 1) {
              this.submitCodeButtonLoading = true;
              this.getCodeFn();
              setTimeout(() => {
                if (this.submitCodeButtonLoading) {
                  this.getCodeFn();
                }
              }, 5000)
            }else if (type == 3) {
              this.submitByMobileLoading = true;
              this.addByMobile();
            }else if (type == 4) {
              this.pwdVisible = true;
            }else {
              this.submitAddAccountButtonLoading = true;
              addAccount(opt).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.getList();
                this.addAccount.open = false;
                this.reset();
              }).finally(() => {
                this.submitAddAccountButtonLoading = false;
              });
            }
            // }else {
            //   addAccount(opt).then(response => {
            //     this.$modal.msgSuccess("新增成功");
            //     this.getList();
            //     this.addAccount.open = false;
            //     this.reset();
            //   }).finally(() => {
            //     this.submitAddAccountButtonLoading = false;
            //   });
            // }
            // if (this.addAccount.form.channelId == 504) {
            //   if (type == 1) {
            //     this.submitCodeButtonLoading = true;
            //     this.getCodeFn();
            //     setTimeout(() => {
            //       if (this.submitCodeButtonLoading) {
            //         this.getCodeFn();
            //       }
            //     }, 5000)
            //   }else {
            //     this.submitAddAccountButtonLoading = true;
            //     this.addByMobile();
            //   }
            // }else if (this.addAccount.form.isNeedDeviceId == 0) {
            //   this.getCodeFn();
            // }else {
            //   addAccount(this.addAccount.form).then(response => {
            //     this.$modal.msgSuccess("新增成功");
            //     this.getList();
            //     this.addAccount.open = false;
            //     this.reset();
            //   }).finally(() => {
            //     this.submitAddAccountButtonLoading = false;
            //   });
            // }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      addByMobile() {
        this.bindingVisible = true;
        this.submitByMobileLoading = false;
        // jsDeviceInfo(this.addAccount.form).then(res => {
        //   if (res.code == 200) {
        //     this.deviceInfo = res.data;
        //     this.bindingVisible = true;
        //   }
        //   this.submitByMobileLoading = false
        // })
      },
      countDown() {
        if (this.count != 0) {
          this.timer = setTimeout(() => {
            this.count--;
            this.countDown();
          }, 1000)
        }else {
          this.count = 60;
          clearInterval(this.timer)
        }
      },
      //发送手机验证码
      sendCodeFn() {
        // let mobile = this.mobileCodeForm.mobile;
        let opt = Object.assign({}, this.addAccount.form, {});
        opt.mobile = this.mobileCodeForm.mobile;
        opt.installId = this.deviceInfo.iid;
        this.countDown();
        sendCode(opt).then(response => {
          this.$modal.msgSuccess("验证码发送成功");
        });
      },
      // 手机号密码提交
      submitPwd() {
        this.addByPwdLoading = true;
        let opt = Object.assign({}, this.addAccount.form, {});
        opt.mobile = this.mobilePwdForm.mobile;
        opt.pwd = this.mobilePwdForm.password;
        loginByPwd(opt).then(response => {
          this.addByPwdLoading = false;
          if (response.code == 200) {
            this.pwdVisible = false;
            this.mobilePwdForm = {
              mobile: undefined,
              password: undefined
            }
            this.submitAddAccountButtonLoading = false;
            this.getList();
            this.$modal.msgSuccess("新增成功");
            this.addAccount.open = false;
          }
        }).finally(() => {
          this.addByPwdLoading = false;
        });
      },
      //提交验证码
      submitMobile() {
        this.addButtonLoading = true;
        let opt = Object.assign({}, this.addAccount.form, {});
        opt.mobile = this.mobileCodeForm.mobile;
        opt.code = this.mobileCodeForm.code;
        opt.installId = this.deviceInfo.iid;
        smsLogin(opt).then(response => {
          this.addButtonLoading = false;
          if (response.code == 200) {
            this.bindingVisible = false;
            this.mobileCodeForm = {
              mobile: undefined,
              code: undefined
            }
            this.submitAddAccountButtonLoading = false;
            this.getList();
            this.$modal.msgSuccess("新增成功");
            this.addAccount.open = false;
          }
        }).finally(() => {
          this.addButtonLoading = false;
        });
      },
      getCodeFn() {
        getQrcodeByDID(this.addAccount.form).then(res => {
          this.codeSrc = `${res.data.qrcode}`;
          this.expireTime = formatTime(new Date(res.data.expire_time*1000));
          this.codeDialog = true;
          this.submitAddAccountButtonLoading = false;
          this.codeStatus = '';
          this.timer = setInterval(() => {
            // let opt = Object.assign({}, this.addAccount.form, {installId: res.data.iid, token: res.data.token, userId: this.chooseUserId});
            let opt = Object.assign({}, this.addAccount.form, {installId: res.data.iid, deviceId: res.data.did, token: res.data.token});
            if (this.chooseArr.length) {
              opt.userId = this.chooseArr[this.chooseArr.length - 1];
            }
            checkQrcode(opt).then(response => {
              console.log(response, 'getQrcodeByDID')
              if (response.code == 500) {
                this.codeDialog = false;
                clearTimeout(this.timer);
                return;
              }
              this.codeStatus = response.data.status;
              if (this.codeStatus == 'expired') {
                // this.getCodeFn();
                clearTimeout(this.timer);
              }else if (this.codeStatus == 'confirmed') {
                this.codeDialog = false;
                this.getList();
                this.addAccount.open = false;
                this.reset();
                clearTimeout(this.timer);
              }else if (this.codeStatus == '' || this.codeStatus == undefined) {
                this.codeDialog = false;
                clearTimeout(this.timer);
              }
            })
          }, 5000)
        }).finally(() => {
          this.submitAddAccountButtonLoading = false;
          this.submitCodeButtonLoading = false;
        })
      },
      /** 取消提交添加账号 */
      cancel(formName) {
        this.$refs[formName].clearValidate(['dailyLimitQuota', 'totalLimitQuota', 'douyinId', 'ck'])
        this.addAccount.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        const fixedAmounts = this.addAccount.form.fixedAmounts;
        this.proxyModule = 0
        this.proxyAreaCode = ''
        this.proxyAreaName = ''
        this.proxyArea = [];
        this.addAccount.form = {
          douyinId: undefined,
          ck: undefined,
          groupId: 0,
          deviceId: '',
          installId: '',
          fixedAmounts: fixedAmounts
        }
      },
      handleFileUploadProgress() {
        this.submitFileFormLoading = true;
        this.upload.isUploading = true;
      },
      //导入账号成功回调
      handleFileSuccess(response, file, fileList) {
        this.submitFileFormLoading = false;
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$modal.msgSuccess(response.msg);
        this.getList();
      },
      //导入账号失败
      handleFileError() {
        this.submitFileFormLoading = false;
      },
      //下载导入模板
      importTemplate() {
        this.$download.excel('/account/importTemplate/' + this.upload.channelId);
      },
      //提交账号导入按钮
      submitFileForm() {
        this.$refs.upload.submit();
        this.upload.channelId = undefined;
      },
      //新增固额表单
      addFixedAmount(index) {
        this.addAccount.form.fixedAmounts.push({
          key: index,
          amount: '',
          payUrl: '',
        })
      },
      //删除固额表单
      removeFixedAmount(item) {
        var index = this.addAccount.form.fixedAmounts.indexOf(item)
        if (index !== -1) {
          this.addAccount.form.fixedAmounts.splice(index, 1)
        }
      },
      //发送手机验证码
      sendMobileCode() {
        let mobile = this.mobileCodeForm.mobile;
        sendMobileCode(mobile).then(response => {
          this.$modal.msgSuccess("验证码发送成功");
        });
      },
      //提交验证码
      submitMobileCode() {
        let mobile = this.mobileCodeForm.mobile;
        let code = this.mobileCodeForm.code;
        submitMobileCode(mobile, code).then(response => {
          let account = response.data;
          this.addAccount.form.deviceId = account.deviceId;
          this.addAccount.form.installId = account.installId;
          this.addAccount.form.ck = account.ck;
          this.sendMobileCodeInnerVisible = false;
        });
      },
      handleChange(val) {
        console.log(val, '11')
        if (val.length) {
          this.proxyAreaCode = val[val.length - 1];
        }else {
          this.proxyAreaCode = '';
        }
      },
      //获取地区
      regionDing(data){
        if (!data) {
          // this.regionDialog = true
          this.proxyAreaCode=''
          this.proxyAreaName=''
          this.regionModule=''
        }
         areaList(data).then(res => {
          this.regionList = res.data
        });
      },
      //地区搜索
      handleSearch(){
        this.regionDing(this.regionModule)
      },
      //选中地区
      handleChoice(data){
        this.proxyAreaCode=data.id,
        this.proxyAreaName=data.label
      },
      handleBd(data){
        this.regionDialog = false
        this.proxyAreaCode=data.id,
        this.proxyAreaName=data.label
      }
    }
  }

</script>

<style lang="scss" scoped>
@media screen and (max-width:950px){
.fz{
   font-size: 16px;
 }
 .min-btn{
   display: block;
   margin-left: 0;
 }
}
  .min-div{
   margin-bottom: 20px;
 }
  .clearfix-sun {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .region ::v-deep .el-dialog__body{
    padding-top: 0;
  }
  .region-head{
    padding-bottom: 20px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
  .region-input ::v-deep .el-input__inner{
    border: 1px solid #1890ff !important;
    border-radius: 0 !important;
  }
  .city-choice{
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  .city-itme{
    border: 1px solid #dddddd;
    padding: 5px 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 15px;
    cursor: pointer;
    float: left;
    margin: 10px 0;
    margin-right: 10px;
  }
  .city-itme-btn{
    padding: 5px 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 15px;
    cursor: pointer;
    float: left;
    margin: 10px 0;
    margin-right: 10px;
    border: 1px solid #2f55d4;
    background: #eaf1ff;
  }
  .box-code {
    position: relative;
    margin-top: 10px;
    .code-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    .box-state {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(0, 0, 0, 0.3);
      z-index: 999;
      .text {
        padding: 10px;
        background: #000;
        color: #fff;
      }
    }
  }
  .time {
    text-align: center;
    margin-top: 4px;
  }
</style>
